<template>
  <div class="add-homeowner">
    <div class="form-container">
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="homeownerForm" 
        label-width="120px"
        class="homeowner-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="小区名称" prop="communityId">
                <el-select 
                  v-model="form.communityId" 
                  placeholder="请选择小区"
                  @change="handleCommunityChange"
                  style="width: 100%"
                >
                  <el-option
                    v-for="community in communityList"
                    :key="community.communityId"
                    :label="community.communityName"
                    :value="community.communityId"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="房间号" prop="roomId">
                <el-cascader
                  v-model="roomCascader"
                  :options="roomOptions"
                  :props="cascaderProps"
                  placeholder="---级联楼栋-单元-房间号选择---"
                  @change="handleRoomChange"
                  style="width: 100%"
                  :disabled="!form.communityId"
                ></el-cascader>
              </el-form-item>

              <el-form-item label="姓名" prop="homeownerName">
                <el-input 
                  v-model="form.homeownerName" 
                  placeholder="请输入"
                  maxlength="20"
                ></el-input>
              </el-form-item>

              <el-form-item label="性别" prop="homeownerSex">
                <el-radio-group v-model="form.homeownerSex">
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="住户身份" prop="status">
                <el-select v-model="form.status" placeholder="请选择住户身份" style="width: 100%">
                  <el-option label="业主本人" :value="1"></el-option>
                  <el-option label="家庭成员" :value="2"></el-option>
                  <el-option label="租户" :value="3"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="业主卡号" prop="homeownerCard">
                <el-input 
                  v-model="form.homeownerCard" 
                  placeholder="请输入"
                  maxlength="20"
                ></el-input>
              </el-form-item>

              <el-form-item label="入住时间" prop="homeownerTime">
                <el-date-picker
                  v-model="form.homeownerTime"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="手机号" prop="homeownerPhone">
                <el-input 
                  v-model="form.homeownerPhone" 
                  placeholder="请输入"
                  maxlength="11"
                ></el-input>
              </el-form-item>
            </div>

            <!-- 人脸采集 -->
            <div class="form-right">
              <div class="face-collection">
                <div class="face-box" @click="handleFaceCollection">
                  <i class="el-icon-plus face-icon"></i>
                  <div class="face-text">人脸采集</div>
                  <div class="face-subtitle">点击打开摄像头</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 其它信息 -->
        <div class="form-section">
          <h3 class="section-title">其它信息</h3>
          <div class="form-content">
            <div class="form-left">
              <el-form-item label="微信号" prop="homeownerWechat">
                <el-input 
                  v-model="form.homeownerWechat" 
                  placeholder="请输入"
                  maxlength="30"
                ></el-input>
              </el-form-item>

              <el-form-item label="身份证号" prop="homeownerIdcard">
                <el-input 
                  v-model="form.homeownerIdcard" 
                  placeholder="请输入"
                  maxlength="18"
                ></el-input>
              </el-form-item>

              <el-form-item label="户籍地址" prop="homeownerAddress">
                <div style="display: flex; align-items: center; gap: 10px;">
                  <el-cascader
                    v-model="addressCascader"
                    :options="addressOptions"
                    :props="cascaderProps"
                    placeholder="---级联选择---"
                    style="flex: 1"
                    :loading="addressLoading"
                    @change="handleAddressChange"
                    clearable
                    filterable
                  ></el-cascader>
                  <el-button 
                    size="small" 
                    type="primary" 
                    :loading="addressLoading"
                    @click="refreshAddressData"
                    title="刷新地址数据"
                  >
                    <i class="el-icon-refresh"></i>
                  </el-button>
                </div>
                <div style="font-size: 12px; color: #999; margin-top: 5px;">
                  当前包含 {{ addressOptions.length }} 个省份，{{ getTotalCities() }} 个城市，{{ getTotalDistricts() }} 个区县的地址数据
                </div>
              </el-form-item>

              <el-form-item label="备注" prop="homeownerDesc">
                <el-input 
                  v-model="form.homeownerDesc" 
                  type="textarea"
                  :rows="4"
                  placeholder="请输入"
                  maxlength="200"
                ></el-input>
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
          <el-button @click="handleBack">返回</el-button>
          <el-button type="warning" @click="handleTestConnection">测试连接</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { homeownerApi } from '@/api/homeowner'
import { commonApi } from '@/api/common'

export default {
  name: 'AddHomeowner',
  data() {
    return {
      saving: false,
      form: {
        homeownerName: '',
        homeownerPhone: '',
        homeownerSex: 1,
        homeownerCard: '',
        homeownerTime: '',
        homeownerWechat: '',
        homeownerIdcard: '',
        homeownerAddress: '',
        communityId: '',
        buildingId: '',
        roomId: '',
        status: 1,
        validityPeriod: 0,
        homeownerDesc: '',
        liveStatus: 0, // 默认已迁入
        homeownerDeposit: 0
      },
      rules: {
        homeownerName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        homeownerPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        homeownerSex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        communityId: [
          { required: true, message: '请选择小区', trigger: 'change' }
        ],
        roomId: [
          { required: true, message: '请选择房间', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择住户身份', trigger: 'change' }
        ],
        homeownerIdcard: [
          { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
        ]
      },
      communityList: [],
      buildingList: [],
      roomList: [],
      roomCascader: [],
      addressCascader: [],
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      roomOptions: [],
      addressOptions: [],
      addressLoading: false
    }
  },
  mounted() {
    this.loadCommunityList()
    this.loadAddressData()
  },
  methods: {
    // 加载小区列表
    async loadCommunityList() {
      try {
        const response = await commonApi.getAllCommunities()
        if (response.code === 200) {
          this.communityList = response.data || []
        } else {
          this.$message.error('获取小区列表失败')
        }
      } catch (error) {
        console.error('获取小区列表失败:', error)
        this.$message.error('获取小区列表失败')
      }
    },

    // 加载地址数据
    async loadAddressData() {
      this.addressLoading = true
      try {
        // 直接使用本地模拟数据，避免跨域问题
        console.log('加载地址数据...')
        this.loadMockAddressData()
        console.log('地址数据加载完成，共', this.addressOptions.length, '个省份')
      } catch (error) {
        console.error('加载地址数据失败:', error)
        this.loadMockAddressData()
      } finally {
        this.addressLoading = false
      }
    },

    // 刷新地址数据
    async refreshAddressData() {
      this.addressLoading = true
      try {
        console.log('刷新地址数据...')
        
        // 尝试从外部API获取最新数据
        const success = await this.loadExternalAddressData()
        
        if (success) {
          this.$message.success('地址数据刷新成功')
        } else {
          // 外部API失败，使用本地数据
          this.loadMockAddressData()
          this.$message.info('使用本地地址数据（共' + this.addressOptions.length + '个省份）')
        }
      } catch (error) {
        console.error('刷新地址数据失败:', error)
        this.loadMockAddressData()
        this.$message.warning('刷新失败，使用本地地址数据')
      } finally {
        this.addressLoading = false
      }
    },

    // 尝试加载外部API数据（备用方案）
    async loadExternalAddressData() {
      try {
        console.log('尝试加载外部API数据...')
        // 尝试使用第一个API
        const response = await commonApi.getRegionData()
        if (response && response.data) {
          this.addressOptions = this.formatAddressData(response.data)
          console.log('外部API数据加载成功')
          return true
        }
      } catch (error) {
        console.warn('第一个API失败:', error.message)
      }

      try {
        // 尝试使用备用API
        const response = await commonApi.getChinaRegionData()
        if (response && response.data) {
          this.addressOptions = this.formatChinaRegionData(response.data)
          console.log('备用API数据加载成功')
          return true
        }
      } catch (error) {
        console.warn('备用API失败:', error.message)
      }

      return false
    },

    // 格式化地址数据（第一个API）
    formatAddressData(data) {
      if (!data || !Array.isArray(data)) return []
      
      return data.map(province => ({
        id: province.code || province.id,
        name: province.name,
        children: province.children ? province.children.map(city => ({
          id: city.code || city.id,
          name: city.name,
          children: city.children ? city.children.map(district => ({
            id: district.code || district.id,
            name: district.name
          })) : []
        })) : []
      }))
    },

    // 格式化中国行政区划数据
    formatChinaRegionData(data) {
      if (!data || typeof data !== 'object') return []
      
      return Object.keys(data).map(provinceCode => {
        const province = data[provinceCode]
        return {
          id: provinceCode,
          name: province.name,
          children: Object.keys(province.children || {}).map(cityCode => {
            const city = province.children[cityCode]
            return {
              id: cityCode,
              name: city.name,
              children: Object.keys(city.children || {}).map(districtCode => {
                const district = city.children[districtCode]
                return {
                  id: districtCode,
                  name: district.name
                }
              })
            }
          })
        }
      })
    },

    // 加载模拟地址数据
    loadMockAddressData() {
      this.addressOptions = [
        {
          id: '110000',
          name: '北京市',
          children: [
            {
              id: '110100',
              name: '北京市',
              children: [
                { id: '110101', name: '东城区' },
                { id: '110102', name: '西城区' },
                { id: '110105', name: '朝阳区' },
                { id: '110106', name: '丰台区' },
                { id: '110107', name: '石景山区' },
                { id: '110108', name: '海淀区' },
                { id: '110109', name: '门头沟区' },
                { id: '110111', name: '房山区' },
                { id: '110112', name: '通州区' },
                { id: '110113', name: '顺义区' },
                { id: '110114', name: '昌平区' },
                { id: '110115', name: '大兴区' },
                { id: '110116', name: '怀柔区' },
                { id: '110117', name: '平谷区' },
                { id: '110118', name: '密云区' },
                { id: '110119', name: '延庆区' }
              ]
            }
          ]
        },
        {
          id: '310000',
          name: '上海市',
          children: [
            {
              id: '310100',
              name: '上海市',
              children: [
                { id: '310101', name: '黄浦区' },
                { id: '310104', name: '徐汇区' },
                { id: '310105', name: '长宁区' },
                { id: '310106', name: '静安区' },
                { id: '310107', name: '普陀区' },
                { id: '310109', name: '虹口区' },
                { id: '310110', name: '杨浦区' },
                { id: '310112', name: '闵行区' },
                { id: '310113', name: '宝山区' },
                { id: '310114', name: '嘉定区' },
                { id: '310115', name: '浦东新区' },
                { id: '310116', name: '金山区' },
                { id: '310117', name: '松江区' },
                { id: '310118', name: '青浦区' },
                { id: '310120', name: '奉贤区' },
                { id: '310151', name: '崇明区' }
              ]
            }
          ]
        },
        {
          id: '440000',
          name: '广东省',
          children: [
            {
              id: '440100',
              name: '广州市',
              children: [
                { id: '440103', name: '荔湾区' },
                { id: '440104', name: '越秀区' },
                { id: '440105', name: '海珠区' },
                { id: '440106', name: '天河区' },
                { id: '440111', name: '白云区' },
                { id: '440112', name: '黄埔区' },
                { id: '440113', name: '番禺区' },
                { id: '440114', name: '花都区' },
                { id: '440115', name: '南沙区' },
                { id: '440117', name: '从化区' },
                { id: '440118', name: '增城区' }
              ]
            },
            {
              id: '440300',
              name: '深圳市',
              children: [
                { id: '440303', name: '罗湖区' },
                { id: '440304', name: '福田区' },
                { id: '440305', name: '南山区' },
                { id: '440306', name: '宝安区' },
                { id: '440307', name: '龙岗区' },
                { id: '440308', name: '盐田区' },
                { id: '440309', name: '龙华区' },
                { id: '440310', name: '坪山区' },
                { id: '440311', name: '光明区' }
              ]
            },
            {
              id: '440600',
              name: '佛山市',
              children: [
                { id: '440604', name: '禅城区' },
                { id: '440605', name: '南海区' },
                { id: '440606', name: '顺德区' },
                { id: '440607', name: '三水区' },
                { id: '440608', name: '高明区' }
              ]
            }
          ]
        },
        {
          id: '320000',
          name: '江苏省',
          children: [
            {
              id: '320100',
              name: '南京市',
              children: [
                { id: '320102', name: '玄武区' },
                { id: '320104', name: '秦淮区' },
                { id: '320105', name: '建邺区' },
                { id: '320106', name: '鼓楼区' },
                { id: '320111', name: '浦口区' },
                { id: '320113', name: '栖霞区' },
                { id: '320114', name: '雨花台区' },
                { id: '320115', name: '江宁区' },
                { id: '320116', name: '六合区' },
                { id: '320117', name: '溧水区' },
                { id: '320118', name: '高淳区' }
              ]
            },
            {
              id: '320200',
              name: '无锡市',
              children: [
                { id: '320202', name: '锡山区' },
                { id: '320203', name: '惠山区' },
                { id: '320204', name: '滨湖区' },
                { id: '320205', name: '梁溪区' },
                { id: '320206', name: '新吴区' },
                { id: '320281', name: '江阴市' },
                { id: '320282', name: '宜兴市' }
              ]
            }
          ]
        },
        {
          id: '330000',
          name: '浙江省',
          children: [
            {
              id: '330100',
              name: '杭州市',
              children: [
                { id: '330102', name: '上城区' },
                { id: '330105', name: '拱墅区' },
                { id: '330106', name: '西湖区' },
                { id: '330108', name: '滨江区' },
                { id: '330109', name: '萧山区' },
                { id: '330110', name: '余杭区' },
                { id: '330111', name: '富阳区' },
                { id: '330112', name: '临安区' },
                { id: '330113', name: '临平区' },
                { id: '330114', name: '钱塘区' },
                { id: '330122', name: '桐庐县' },
                { id: '330127', name: '淳安县' },
                { id: '330182', name: '建德市' }
              ]
            },
            {
              id: '330200',
              name: '宁波市',
              children: [
                { id: '330203', name: '海曙区' },
                { id: '330205', name: '江北区' },
                { id: '330206', name: '北仑区' },
                { id: '330211', name: '镇海区' },
                { id: '330212', name: '鄞州区' },
                { id: '330213', name: '奉化区' },
                { id: '330225', name: '象山县' },
                { id: '330226', name: '宁海县' },
                { id: '330281', name: '余姚市' },
                { id: '330282', name: '慈溪市' }
              ]
            }
          ]
        },
        {
          id: '370000',
          name: '山东省',
          children: [
            {
              id: '370100',
              name: '济南市',
              children: [
                { id: '370102', name: '历下区' },
                { id: '370103', name: '市中区' },
                { id: '370104', name: '槐荫区' },
                { id: '370105', name: '天桥区' },
                { id: '370112', name: '历城区' },
                { id: '370113', name: '长清区' },
                { id: '370114', name: '章丘区' },
                { id: '370115', name: '济阳区' },
                { id: '370116', name: '莱芜区' },
                { id: '370117', name: '钢城区' },
                { id: '370124', name: '平阴县' },
                { id: '370126', name: '商河县' }
              ]
            },
            {
              id: '370200',
              name: '青岛市',
              children: [
                { id: '370202', name: '市南区' },
                { id: '370203', name: '市北区' },
                { id: '370211', name: '黄岛区' },
                { id: '370212', name: '崂山区' },
                { id: '370213', name: '李沧区' },
                { id: '370214', name: '城阳区' },
                { id: '370215', name: '即墨区' },
                { id: '370281', name: '胶州市' },
                { id: '370283', name: '平度市' },
                { id: '370285', name: '莱西市' }
              ]
            }
          ]
        },
        {
          id: '500000',
          name: '重庆市',
          children: [
            {
              id: '500100',
              name: '重庆市',
              children: [
                { id: '500101', name: '万州区' },
                { id: '500102', name: '涪陵区' },
                { id: '500103', name: '渝中区' },
                { id: '500104', name: '大渡口区' },
                { id: '500105', name: '江北区' },
                { id: '500106', name: '沙坪坝区' },
                { id: '500107', name: '九龙坡区' },
                { id: '500108', name: '南岸区' },
                { id: '500109', name: '北碚区' },
                { id: '500110', name: '綦江区' },
                { id: '500111', name: '大足区' },
                { id: '500112', name: '渝北区' },
                { id: '500113', name: '巴南区' },
                { id: '500114', name: '黔江区' },
                { id: '500115', name: '长寿区' },
                { id: '500116', name: '江津区' },
                { id: '500117', name: '合川区' },
                { id: '500118', name: '永川区' },
                { id: '500119', name: '南川区' },
                { id: '500120', name: '璧山区' },
                { id: '500151', name: '铜梁区' },
                { id: '500152', name: '潼南区' },
                { id: '500153', name: '荣昌区' },
                { id: '500154', name: '开州区' },
                { id: '500155', name: '梁平区' },
                { id: '500156', name: '武隆区' }
              ]
            }
          ]
        },
        {
          id: '510000',
          name: '四川省',
          children: [
            {
              id: '510100',
              name: '成都市',
              children: [
                { id: '510104', name: '锦江区' },
                { id: '510105', name: '青羊区' },
                { id: '510106', name: '金牛区' },
                { id: '510107', name: '武侯区' },
                { id: '510108', name: '成华区' },
                { id: '510112', name: '龙泉驿区' },
                { id: '510113', name: '青白江区' },
                { id: '510114', name: '新都区' },
                { id: '510115', name: '温江区' },
                { id: '510116', name: '双流区' },
                { id: '510117', name: '郫都区' },
                { id: '510118', name: '新津区' },
                { id: '510121', name: '金堂县' },
                { id: '510129', name: '大邑县' },
                { id: '510131', name: '蒲江县' },
                { id: '510181', name: '都江堰市' },
                { id: '510182', name: '彭州市' },
                { id: '510183', name: '邛崃市' },
                { id: '510184', name: '崇州市' },
                { id: '510185', name: '简阳市' }
              ]
            }
          ]
        }
      ]
    },

    // 小区选择变化
    async handleCommunityChange(communityId) {
      this.form.buildingId = ''
      this.form.roomId = ''
      this.roomCascader = []
      this.roomOptions = []
      
      if (communityId) {
        await this.loadBuildingList(communityId)
      }
    },

    // 加载楼宇列表
    async loadBuildingList(communityId) {
      try {
        const response = await commonApi.getBuildingsByCommunityId(communityId)
        if (response.code === 200) {
          const buildings = response.data || []
          
          // 为每个楼宇加载房间数据
          for (let building of buildings) {
            building.children = await this.loadRoomList(building.buildingId)
          }
          
          this.roomOptions = buildings.map(building => ({
            id: building.buildingId,
            name: building.buildingName,
            children: building.children
          }))
        } else {
          console.warn('获取楼宇列表失败，使用模拟数据')
          this.loadMockBuildingData()
        }
      } catch (error) {
        console.error('获取楼宇列表失败，使用模拟数据:', error)
        this.loadMockBuildingData()
      }
    },

    // 加载模拟楼宇数据
    loadMockBuildingData() {
      const mockBuildings = [
        { 
          id: 'building1', 
          name: '1栋', 
          children: [
            { id: 'room101', name: '101' },
            { id: 'room102', name: '102' },
            { id: 'room201', name: '201' },
            { id: 'room202', name: '202' }
          ]
        },
        { 
          id: 'building2', 
          name: '2栋', 
          children: [
            { id: 'room301', name: '301' },
            { id: 'room302', name: '302' },
            { id: 'room401', name: '401' },
            { id: 'room402', name: '402' }
          ]
        },
        { 
          id: 'building3', 
          name: '3栋', 
          children: [
            { id: 'room501', name: '501' },
            { id: 'room502', name: '502' },
            { id: 'room601', name: '601' },
            { id: 'room602', name: '602' }
          ]
        }
      ]
      this.roomOptions = mockBuildings
    },

    // 加载房间列表
    async loadRoomList(buildingId) {
      try {
        const response = await commonApi.getRoomsByBuildingId(buildingId)
        if (response.code === 200) {
          const rooms = response.data || []
          return rooms.map(room => ({
            id: room.roomId,
            name: room.roomNumber.toString()
          }))
        } else {
          console.warn('获取房间列表失败，使用模拟数据')
          return this.getMockRoomsByBuilding(buildingId)
        }
      } catch (error) {
        console.error('获取房间列表失败，使用模拟数据:', error)
        return this.getMockRoomsByBuilding(buildingId)
      }
    },

    // 根据楼宇ID获取模拟房间数据
    getMockRoomsByBuilding(buildingId) {
      const mockRooms = {
        'building1': [
          { id: 'room101', name: '101' },
          { id: 'room102', name: '102' },
          { id: 'room201', name: '201' },
          { id: 'room202', name: '202' }
        ],
        'building2': [
          { id: 'room301', name: '301' },
          { id: 'room302', name: '302' },
          { id: 'room401', name: '401' },
          { id: 'room402', name: '402' }
        ],
        'building3': [
          { id: 'room501', name: '501' },
          { id: 'room502', name: '502' },
          { id: 'room601', name: '601' },
          { id: 'room602', name: '602' }
        ]
      }
      return mockRooms[buildingId] || []
    },

    // 房间选择变化
    handleRoomChange(value) {
      if (value && value.length === 2) {
        this.form.buildingId = value[0]
        this.form.roomId = value[1]
      } else {
        this.form.buildingId = ''
        this.form.roomId = ''
      }
    },

    // 地址选择变化
    handleAddressChange(value) {
      if (value && value.length === 3) {
        // 获取选中的省市区名称
        const provinceName = this.getAddressNameById(value[0])
        const cityName = this.getAddressNameById(value[1])
        const districtName = this.getAddressNameById(value[2])
        
        this.form.homeownerAddress = `${provinceName}/${cityName}/${districtName}`
      } else {
        this.form.homeownerAddress = ''
      }
    },

    // 根据ID获取地址名称
    getAddressNameById(id) {
      for (const province of this.addressOptions) {
        if (province.id === id) {
          return province.name
        }
        if (province.children) {
          for (const city of province.children) {
            if (city.id === id) {
              return city.name
            }
            if (city.children) {
              for (const district of city.children) {
                if (district.id === id) {
                  return district.name
                }
              }
            }
          }
        }
      }
      return ''
    },

    // 获取总城市数
    getTotalCities() {
      let total = 0
      this.addressOptions.forEach(province => {
        if (province.children) {
          total += province.children.length
        }
      })
      return total
    },

    // 获取总区县数
    getTotalDistricts() {
      let total = 0
      this.addressOptions.forEach(province => {
        if (province.children) {
          province.children.forEach(city => {
            if (city.children) {
              total += city.children.length
            }
          })
        }
      })
      return total
    },

    // 人脸采集
    handleFaceCollection() {
      this.$message.info('人脸采集功能待实现')
    },

    // 保存
    async handleSave() {
      try {
        await this.$refs.homeownerForm.validate()
        
        this.saving = true
        
        // 处理数据字段
        const formData = { ...this.form }
        
        // 确保数值字段为正确的类型
        if (formData.homeownerDeposit) {
          formData.homeownerDeposit = parseFloat(formData.homeownerDeposit) || 0
        }
        if (formData.validityPeriod) {
          formData.validityPeriod = parseInt(formData.validityPeriod) || 0
        }
        
        console.log('发送的数据:', formData)
        
        const response = await homeownerApi.addHomeowner(formData)
        
        if (response.code === 200) {
          this.$message.success('添加业主成功')
          this.handleBack()
        } else {
          this.$message.error(response.message || '添加业主失败')
        }
      } catch (error) {
        if (error.message) {
          this.$message.error(error.message)
        } else {
          console.error('添加业主失败:', error)
          this.$message.error('添加业主失败')
        }
      } finally {
        this.saving = false
      }
    },

    // 返回
    handleBack() {
      this.$router.go(-1)
    },

    // 测试连接
    async handleTestConnection() {
      try {
        console.log('测试后端连接...')
        const response = await commonApi.testBuildingController()
        console.log('测试响应:', response)
        if (response.code === 200) {
          this.$message.success('后端连接正常: ' + response.data)
        } else {
          this.$message.error('后端连接异常: ' + response.message)
        }
      } catch (error) {
        console.error('测试连接失败:', error)
        this.$message.error('后端连接失败: ' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.add-homeowner {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 1000px;
  margin: 0 auto;
}

.homeowner-form {
  width: 100%;
}

.form-section {
  margin-bottom: 40px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.form-content {
  display: flex;
  gap: 40px;
}

.form-left {
  flex: 1;
}

.form-right {
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.face-collection {
  width: 100%;
}

.face-box {
  width: 160px;
  height: 200px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fafafa;
}

.face-box:hover {
  border-color: #409EFF;
  background-color: #f0f9ff;
}

.face-icon {
  font-size: 32px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.face-text {
  font-size: 16px;
  color: #606266;
  margin-bottom: 5px;
}

.face-subtitle {
  font-size: 12px;
  color: #909399;
}

.form-actions {
  text-align: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.form-actions .el-button {
  margin: 0 10px;
  padding: 12px 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .form-right {
    width: 100%;
    justify-content: center;
  }
  
  .face-box {
    width: 200px;
  }
}
</style>
